"""
Case Type   : CM
Case Name   : 参数enable_log_compress功能验证
Create At   : 2024.6
Owner       : haomeng802
Description :
    1、查看集群状态 cm_ctl query -Cidvp
    2、查询参数enable_log_compress默认值
    3、对集群进行重启，主备切换等操作
    4、查看cma相关log
    5、恢复环境
Expect      :
    1、集群状态正常，数据库节点状态正常
    2、默认值查询成功为on
    3、切换操作成功，重启成功
    4、查看已生成日志，部分日志已被压缩
    5、恢复环境成功
History     :
    2024.4.11 ningyali 增加前置（安装cm）和后置（卸载cm）操作
"""

import os
import unittest

from testcase.utils.ComInstall import CmInstall
from testcase.utils.ComInstall import CmUnInstall
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class CmServer(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.param = 'enable_log_compress'
        self.cma_path = os.path.join(os.path.basename(macro.PG_LOG_PATH),
                                     'cm/cm_agent/pg_log')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.root_nodes = (Node('PrimaryRoot'), Node('Standby1Root'),
                           Node('Standby2Root'))
        self.user_nodes = (Node('PrimaryDbUser'), Node('Standby1DbUser'),
                           Node('Standby2DbUser'))
        self.common = Common()

        text = '----prestep1:安装cm;expect:执行成功----'
        self.log.info(text)
        self.install_pkg_path = os.path.dirname(macro.DB_SCRIPT_PATH)
        self.cm = CmInstall(self.install_pkg_path, self.pri_sh.node.ssh_user)
        res = self.cm.update_xml_for_cm(*self.root_nodes)
        self.assertGreater(res.count('cmDir'), 1, f'执行失败: {text}')

        res = self.cm.cm_install(self.user_nodes[0])
        self.assertIn('Install CM tool success', res, f'执行失败: {text}')

    def test_cm_server(self):
        text = '-----step1:查看集群状态; expect:集群状态正常-----'
        self.log.info(text)
        status = self.pri_sh.exec_cm_ctl(mode='query', param='-Cv')
        self.log.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败' + text)

        text = '----step2:查询参数enable_log_compress默认值; expect:默认值查询成功为on----'
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'cm_ctl list --param --agent | grep {self.param}'
        self.log.info(cmd)
        show_param1 = self.user_nodes[0].sh(cmd).result()
        self.log.info(show_param1)
        self.assertEqual('on',
                         show_param1.splitlines()[0].split('=')[-1].strip(),
                         '参数默认值不为on')

        text = '-----step3:对集群进行重启，主备切换等操作 expect:切换操作成功，重启成功-----'
        self.log.info(text)

        stop = self.pri_sh.exec_cm_ctl(mode='stop')
        self.log.info(stop)
        start = self.pri_sh.exec_cm_ctl(mode='start')
        self.log.info(start)
        switch1 = self.pri_sh.exec_cm_ctl('switchover', '-n 2',
                                          f'-D {macro.DB_INSTANCE_PATH}')
        self.log.info(switch1)
        switch2 = self.pri_sh.exec_cm_ctl('switchover', '-n 3',
                                          f'-D {macro.DB_INSTANCE_PATH}')
        self.log.info(switch2)
        switch3 = self.pri_sh.exec_cm_ctl('switchover', '-n 1',
                                          f'-D {macro.DB_INSTANCE_PATH}')
        self.log.info(switch3)

        text = '-----step4:查看cma相关log  expect:查看已生成日志，部分日志已被压缩-----'
        self.log.info(text)
        cat = f'cd {self.cma_path};ls -al *.gz | wc -l'
        self.log.info(cat)
        res = self.user_nodes[0].sh(cat).result()
        self.log.info(res)
        self.assertNotEqual(0, res, '未产生压缩日志')

    def tearDown(self):
        text = '----poststep1:卸载cm;expect:执行成功----'
        self.log.info(text)
        self.un_cm = CmUnInstall(self.install_pkg_path,
                                 self.pri_sh.node.ssh_user)
        res = self.un_cm.cm_uninstall(
            self.user_nodes[0], '--deleteData --deleteBinary')
        self.assertIn('Uninstall CM tool success', res, f'执行失败: {text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
